<template>
  <div>
    <el-dialog
      :visible.sync="visible"
      title="编辑定价规则"
      width="60%"
      :before-close="handleClose"
    >
      <!-- 定价规则表单 -->
      <el-form
        :model="priceRuleEditForm"
        :rules="priceRuleEditFormRules"
        ref="priceRuleEditFormRef"
        label-width="130px"
        label-position="right"
      >
        <el-form-item label="定价类型" prop="type">
          <el-select v-model="priceRuleEditForm.type" placeholder="请选择">
            <el-option label="按购销合同价" value="1"></el-option>
            <el-option label="按服务实际成本价" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="统一价"
          prop="price"
          v-show="priceRuleEditForm.type == 1"
          :rules="
            priceRuleEditForm.type == 1
              ? [
                  { required: true, message: '请输入', trigger: 'blur' },
                  { validator: decimalValid, trigger: 'blur' }
                ]
              : []
          "
        >
          <el-input
            placeholder="请输入"
            v-model="priceRuleEditForm.price"
            oninput="value=value.replace(/[^\d.]/g,'')"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="统一增补价"
          prop="premium"
          v-show="priceRuleEditForm.type == 2"
          :rules="
            priceRuleEditForm.type == 2
              ? [
                  { required: true, message: '请输入', trigger: 'blur' },
                  { validator: decimalValid, trigger: 'blur' }
                ]
              : []
          "
        >
          <el-input
            placeholder="请输入"
            v-model="priceRuleEditForm.premium"
            oninput="value=value.replace(/[^\d.]/g,'')"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="结算折扣"
          prop="discount"
          v-show="priceRuleEditForm.type == 2"
          :rules="
            priceRuleEditForm.type == 2
              ? [
                  { required: true, message: '请输入', trigger: 'blur' },
                  { validator: decimalValid, trigger: 'blur' }
                ]
              : []
          "
        >
          <el-input
            placeholder="请输入结算折扣，结算价格=（服务成本+统一增补价）*结算折扣"
            v-model="priceRuleEditForm.discount"
            oninput="value=value.replace(/[^\d.]/g,'')"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="定价规则有效期" required>
          <el-col :span="11">
            <el-form-item prop="start_time">
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="priceRuleEditForm.start_time"
                style="width: 100%"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item prop="end_time">
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="priceRuleEditForm.end_time"
                style="width: 100%"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="priceRuleEditForm.remark"
            show-word-limit
            maxlength="500"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="设置差异价"
          prop="is_diff"
          v-show="priceRuleEditForm.type == 1"
        >
          <el-switch v-model="priceRuleEditForm.is_diff"></el-switch>
        </el-form-item>
      </el-form>

      <div v-show="priceRuleEditForm.type == 1 && priceRuleEditForm.is_diff">
        <!-- 差异价规则表 -->
        <el-button icon="el-icon-upload" @click="btachAddDiffRule">
          批量新增差异价规则
        </el-button>
        <el-table
          :data="diffTableEditData"
          border
          style="width: 100%"
          :row-class-name="tableRowClassName"
        >
          <el-table-column type="index" label="序号"> </el-table-column>
          <el-table-column prop="id" label="差异价规则ID" width="100px">
          </el-table-column>
          <el-table-column prop="area" label="地区【ID】">
            <template slot-scope="scope">
              <el-cascader
                :options="options"
                :props="props"
                clearable
                filterable
                :show-all-levels="false"
                v-model="scope.row.area"
                ref="myCascader"
                @change="changeArea(scope.row)"
              ></el-cascader>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="合同价">
            <template slot-scope="scope">
              <el-input
                placeholder="请输入"
                v-model="scope.row.price"
                oninput="value=value.replace(/[^\d.]/g,'')"
              >
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-link
                type="warning"
                v-show="!scope.row.editRowVisible"
                @click="copyColumn(scope.row)"
              >
                复制
              </el-link>
              &nbsp;
              <el-link type="danger" @click="disable(scope.row.index)">
                删除
              </el-link>
            </template>
          </el-table-column>
        </el-table>

        <div class="addColumn">
          <el-button type="text" icon="el-icon-plus" @click="addColumnRule">
            增加差异规则
          </el-button>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button class="theme-background-color" @click="editPriceRuleData"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import regionData from '../../assets/js/regionChoose.js'
export default {
  props: {
    // priceRuleEditForm: {
    //   type: Object,
    //   default: function () {
    //     return {}
    //   }
    // },
    // diffTableEditData: {
    //   type: Array,
    //   default: function () {
    //     return {}
    //   }
    // },
    priceRuleId: {
      type: [String, Number],
      default: function () {
        return {}
      }
    },
    priceRuleEditDialogVisible: {
      type: Boolean,
      default: function () {
        return {}
      }
    }
  },
  data() {
    var decimalValid = (rule, value, callback) => {
      // console.log(rule)
      value = value + ''
      if (value.indexOf('.') !== -1 && value.split('.').length > 2) {
        // 防止输入多个小数点
        callback(new Error('输入正确格式'))
      } else {
        // 不足补位
        value = Number(value).toFixed(2)
        // this.priceRuleEditForm.price = value
        this.priceRuleEditForm[rule.field] = value
        // console.log(this.priceRuleEditForm)
        callback()
      }
    }
    return {
      visible: this.priceRuleEditDialogVisible,
      priceRuleEditForm: {
        type: '',
        price: '',
        premium: '',
        discount: '',
        start_time: '',
        end_time: '',
        remark: '',
        is_diff: false,
        diff: []
      },
      priceRuleEditFormRules: {
        type: [{ required: true, message: '请选择', trigger: 'change' }],
        start_time: [
          {
            required: true,
            message: '请选择日期',
            trigger: ['blur', 'change']
          }
        ],
        end_time: [
          {
            required: true,
            message: '请选择日期',
            trigger: ['blur', 'change']
          }
        ]
      },
      decimalValid,

      // 差异价规则表
      diffTableEditData: [],
      options: [],
      props: {
        checkStrictly: true,
        value: 'code',
        label: 'name',
        children: 'childs'
      }
    }
  },
  created() {
    this.getOptions()
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      //   把每一行的索引放进row
      row.index = rowIndex
    },
    changeArea(row) {
      // console.log(this.$refs.myCascader.getCheckedNodes())
      row.region_name = this.$refs.myCascader.getCheckedNodes().label
    },
    copyColumn(row) {
      var newRow = Object.assign({}, row)
      newRow.id = ''
      newRow.editRowVisible = true
      // console.log(newRow)
      this.diffTableEditData.splice(row.index + 1, 0, newRow)
      // console.log(this.productTable)
    },
    async disable(row) {
      // if (row.id) {
      //   const { data: res } = await this.$http.post(
      //     '/admin/goods/delDiffPrice',
      //     {
      //       id: row.id
      //     }
      //   )
      //   if (res.meta.status !== 200) {
      //     return this.$message.error(res.meta.msg)
      //   }
      // }
      // this.diffTableEditData.splice(row.index, 1)
    },
    addColumnRule() {
      this.diffTableEditData.push({
        id: '',
        area: '',
        region_name: '',
        price: '',
        editRowVisible: true
      })
    },
    getOptions() {
      var arr = regionData
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr[i].childs.length; j++) {
          delete arr[i].childs[j].childs
        }
      }
      this.options = arr
    },
    async getPriceDetail() {
      const { data: res } = await this.$http.post(
        '/admin/provider_product/priceDetail',
        {
          id: this.priceRuleId
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.priceRuleEditForm = JSON.parse(JSON.stringify(res.data))
      this.priceRuleEditForm.is_diff = res.data.diff.length > 0
      this.diffTableEditData = this.priceRuleEditForm.diff
      console.log(this.priceRuleEditForm)
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          this.resetAllData()
          this.$emit('update:priceRuleEditDialogVisible', false)
          done()
        })
        .catch((_) => {})
    },
    closeDialog() {
      this.resetAllData()
      this.$emit('update:priceRuleEditDialogVisible', false)
    },
    editPriceRuleData() {
      this.$refs.priceRuleEditFormRef.validate(async (valid) => {
        if (!valid) return
        console.log(this.priceRuleEditForm)
        if (
          this.priceRuleEditForm.is_diff &&
          this.diffTableEditData.length === 0
        ) {
          return this.$message.error('请配置差异价规则')
        }
        var diff = []
        for (let i = 0; i < this.diffTableEditData.length; i++) {
          const item = {}
          item.price_id = this.priceRuleId
          item.id = this.diffTableEditData[i].id
          item.area = this.diffTableEditData[i].area[1]
          item.provider_id = 1001
          item.price = this.diffTableEditData[i].price
          diff.push(item)
        }
        var postData = Object.assign({}, this.priceRuleEditForm)
        postData.id = this.priceRuleId
        postData.diff = diff
        const { data: res } = await this.$http.post(
          '/admin/provider_product/editPrice',
          postData
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('编辑定价规则成功')
        this.visible = false
        this.$emit('update:priceRuleEditDialogVisible', false)
        this.resetAllData()
      })
    },
    btachAddDiffRule() {
      this.$message.info('功能正在研发中，静侯佳音~')
    },
    // 清空数据
    resetAllData() {
      // 清空校验
      this.$refs.priceRuleFormRef.resetFields()
      this.diffTableEditData = []
    }
  },
  watch: {
    priceRuleEditDialogVisible() {
      this.visible = this.priceRuleEditDialogVisible
      if (this.visible) this.getPriceDetail()
    }
  }
}
</script>
<style lang="less" scoped>
.el-form {
  width: 90%;
  margin-left: 15px;
  .el-select {
    width: 100%;
  }
}
.addColumn {
  margin-top: -16px;
  text-align: center;
  border: 1px solid #eee;
  margin-bottom: 10px;
}
.line {
  text-align: center;
}
</style>
